package org.example.queueadmin.log;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.Instant;

public interface MessageLogRepository extends JpaRepository<MessageLog, Long> {
    
    Page<MessageLog> findByTaskIdOrderByTimestampDesc(Long taskId, Pageable pageable);
    
    Page<MessageLog> findByTaskIdAndLevelOrderByTimestampDesc(Long taskId, MessageLog.LogLevel level, Pageable pageable);
    
    @Modifying
    @Query("DELETE FROM MessageLog m WHERE m.timestamp < :cutoff")
    int deleteOldLogs(@Param("cutoff") Instant cutoff);
    
    @Query("SELECT COUNT(m) FROM MessageLog m WHERE m.taskId = :taskId AND m.success = true")
    long countSuccessfulMessages(@Param("taskId") Long taskId);
    
    @Query("SELECT COUNT(m) FROM MessageLog m WHERE m.taskId = :taskId AND m.success = false")
    long countFailedMessages(@Param("taskId") Long taskId);
}
